<script setup lang="ts">
import { ref } from 'vue'
import { useRoute } from 'vue-router'
import { timeFormat, timeFormat_2 } from '@/hooks/util'
import * as cardCouponsApi from '@/api/cardCoupons'
import { message } from 'ant-design-vue'
import RelatedProduct from './components/RelatedProduct.vue'
import AssociatedList from './components/AssociatedList.vue'

const route = useRoute()

const relatedProductRef = ref()
const associatedListRef = ref()

interface Pagination {
  page: number
  pageSize: number
  total: number
  current?: number
  onChange: Function
  showSizeChanger: boolean
  showQuickJumper: boolean
}

const handlePageChange = (page: any, pageSize: any) => {
  pagination.value.pageSize = pageSize
  searchParams.value.pageSize = pageSize
}

const pagination = ref<Pagination>({
  page: 1,
  pageSize: 10,
  total: 0,
  onChange: handlePageChange,
  showSizeChanger: true,
  showQuickJumper: true
})
let loading = ref<boolean>(false)

interface SearchParams {
  currentPage: number
  pageSize: number
  couponUserId?: string | undefined
}
const searchParams = ref<SearchParams>({
  currentPage: pagination.value.page,
  pageSize: pagination.value.pageSize,
})

const dataSource = ref([])
const columns = [
  {
    title: '卡种ID',
    key: 'idNo',
    width: 180,
  },
  // {
  //   title: '用户ID',
  //   key: 'couponUserId',
  //   width: 180,
  // },
  {
    title: '卡种名称',
    key: 'title',
    width: 180,
  },
  {
    title: '卡种类型',
    key: 'cardType',
    width: 180,
  },
  {
    title: '库存',
    key: 'remainingCount',
    width: 120,
  },
  {
    title: '已用数量',
    key: 'usedCount',
    width: 120,
  },
  {
    title: '总数量',
    key: 'totalCount',
    width: 120,
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: 180,
  },
  {
    key: 'action',
    width: 150,
    fixed: 'right',
  },
]

// 表格多选
const selectedRowKey = ref<Array<any>>([])
const selectedRow = ref<Array<object>>([])
const onSelectChange = (selectedRowKeys: any[], selectedRows: any[]) => {
  selectedRowKey.value = selectedRowKeys
  selectedRow.value = selectedRows
}

// 翻页
const changePage = (e: any) => {
  pagination.value.current = e.current
  pagination.value.pageSize = e.pageSize

  searchParams.value.currentPage = pagination.value.current as number
  getList()
}

const getList = async () => {
  loading.value = true
  try {
    let { state, data, message: msg } = await cardCouponsApi.nineOneDataPageList(searchParams.value)
    if (state === 200) {
      dataSource.value = data.list
      pagination.value.total = Number(data.totalCount)
    } else {
      dataSource.value = []
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
  loading.value = false
}

onMounted(() => {
  // getList()
  getGroupList()
})

// 查询
const formRef = ref()
interface FormState {
  couponUserId?: string
}
const formState = reactive<FormState>({})

const search = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1

  formRef.value.validate().then(() => {
    if (formState.couponUserId != '') {
      searchParams.value.couponUserId = formState.couponUserId
    }
    if(!formState.couponUserId){
      searchParams.value.couponUserId = '0'
    }
    getList()
  })
}

// 重置
const reset = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1

  formRef.value.resetFields()
  formState.couponUserId = searchParams.value.couponUserId as string
  // Reflect.deleteProperty(searchParams.value, 'couponUserId')
  getList()
}

//
import type { SelectProps } from 'ant-design-vue'
const authorizationList = ref<SelectProps['options']>([])
const getGroupList = async () => {
  try {
    let { state, data, message: msg } = await cardCouponsApi.listCardRollNineOne()
    if (state === 200) {
      authorizationList.value = data
      if(data.length > 0){
        handleSelect(data[0].couponUserId)
      } else {
        search()
      }
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 选择授权用户
const handleSelect = (selectValue: any) => {
  console.log('selectValue=', selectValue)
  formState.couponUserId = selectValue
  search()
}

// 关联商品
const relatedProduct = (idNo: string) => {
  console.log(idNo)
  relatedProductRef.value.showModal(idNo, formState.couponUserId)
}

// 取消关联
const cancelAssociation = (idNo: string) => {
  associatedListRef.value.showModal(idNo)
}
</script>

<template>
  <page-container :title="route.meta.title">
    <a-card style="overflow-x: scroll">
      <div class="searchBox">
        <a-form ref="formRef" layout="inline" :model="formState">
          <a-form-item label="选择91卡券账号" name="couponUserId">
            <a-select
              style="width: 150px"
              v-model:value="formState.couponUserId"
              placeholder="请选择"
              @change="handleSelect"
              allowClear
            >
              <a-select-option
                v-for="(item, index) in authorizationList"
                :key="index"
                :value="item.couponUserId"
              >
                {{ item.userNick }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item>
            <a-button type="primary" @click="search">搜索</a-button>
            <a-button @click="reset">重置</a-button>
          </a-form-item>
        </a-form>
      </div>

      <a-alert
        description="小提示：只要鼠标在表格上，按住左Shift键并滚动鼠标滚轮就可以横向滚动表格"
        type="info"
        banner
        style="margin-bottom: 10px; padding: 10px"
      />

      <a-table
        style="overflow-x: scroll"
        :columns="columns"
        :data-source="dataSource"
        :pagination="pagination"
        :loading="loading"
        @change="changePage"
        rowKey="id"
        :row-selection="{ selectedRowKeys: selectedRowKey, onChange: onSelectChange }"
        :scroll="{ x: 100 }"
        size="small"
      >
        <template #emptyText>
          <a-empty description="暂无数据" />
        </template>

        <template #headerCell="{ column }"></template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'idNo'">
            {{ record.idNo }}
          </template>

          <template v-else-if="column.key === 'couponUserId'">
            {{ record.couponUserId }}
          </template>

          <template v-else-if="column.key === 'title'">
            {{ record.title }}
          </template>

          <template v-else-if="column.key === 'cardType'">
            <a-tag color="blue" v-if="record.cardType == 700">循环卡</a-tag>
            <a-tag color="blue" v-if="record.cardType == 800">套卡</a-tag>
            <a-tag color="blue" v-if="record.cardType == 820">唯一卡</a-tag>
            <a-tag color="blue" v-if="record.cardType == 840">重复卡</a-tag>
            <a-tag color="blue" v-if="record.cardType == 850">图片卡</a-tag>
          </template>

          <template v-else-if="column.key === 'createTime'">
            <span v-if="record.createTime != ''">
              {{ timeFormat_2(record.createTime) }}
            </span>
            <span v-else>-</span>
          </template>

          <template v-else-if="column.key === 'remainingCount'">
            {{ record.remainingCount }}
          </template>

          <template v-else-if="column.key === 'totalCount'">
            {{ record.totalCount }}
          </template>

          <template v-else-if="column.key === 'usedCount'">
            {{ record.usedCount }}
          </template>

          <template v-else-if="column.key === 'action'">
            <div style="width: 100px; margin: 0; padding: 0">
              <a @click="relatedProduct(record.idNo)">关联闲鱼商品</a>
            </div>
            <div style="width: 100px; margin: 0; padding: 0">
              <a @click="cancelAssociation(record.idNo)">已关联闲鱼商品</a>
            </div>
          </template>
        </template>
      </a-table>

      <RelatedProduct ref="relatedProductRef"></RelatedProduct>
      <AssociatedList ref="associatedListRef"></AssociatedList>
    </a-card>
  </page-container>
</template>

<style lang="less" scoped>
.hiddenText {
  display: inline-block;
  max-width: 160px;
  overflow: hidden;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  line-height: 16px;
}

.searchBox {
  margin-bottom: 10px;
  display: flex;

  input {
    width: 200px;
    margin-right: 10px;
  }

  button {
    margin-right: 10px;
  }
}

a:hover {
  color: red;
}
</style>
